<template>
    <div class="container flex-container">
        <div class="left">
            <n-card size="large">
                <div class="header">提出一个问题</div>
                <n-form ref="formRef" :model="question" :rules="rules" label-placement="left" size="large">
                    <n-form-item label="标题" path="title">
                        <n-input v-model:value="question.title"/>
                    </n-form-item>
                    <n-form-item label="描述" path="content">
                        <div id="vditor"></div>
                    </n-form-item>
                    <n-form-item label="标签" path="tags">
                        <n-dynamic-tags v-model:value="question.tags" :max="4" type="primary">
                            <template #input="{ submit, deactivate }">
                                <n-auto-complete
                                    ref="autoCompleteInstRef"
                                    v-model:value="autoCompleteValue"
                                    :clear-after-select="true"
                                    :get-show="isShowTagList"
                                    :options="options"
                                    placeholder="请输入"
                                    size="small"
                                    @blur="deactivate"
                                    @select="submit($event)"
                                    @keyup.enter="submit(autoCompleteValue)"
                                />
                            </template>
                            <template #trigger="{ activate, disabled }">
                                <n-button
                                    :disabled="disabled"
                                    dashed
                                    size="small"
                                    type="primary"
                                    @click="activate()"
                                >
                                    <template #icon>
                                        <n-icon>
                                            <Plus/>
                                        </n-icon>
                                    </template>
                                    添加
                                </n-button>
                            </template>
                        </n-dynamic-tags>
                    </n-form-item>
                    <n-form-item label="悬赏">
                        <n-space :vertical="true">
                            <n-input-number v-model:value="question.reward" :clearable="true" :max="userStore.credit"
                                            :min="0">
                                <template #prefix>
                                    ￥
                                </template>
                            </n-input-number>
                            <n-text depth="3">我的余额：{{ userStore.credit }}</n-text>
                        </n-space>
                    </n-form-item>
                </n-form>
                <template #footer>
                    <n-space justify="space-between">
                        <n-button type="primary" @click="handlePublish">发布</n-button>
                        <n-button @click="showDrawer = !showDrawer">补充执行细节</n-button>
                    </n-space>
                </template>
            </n-card>
        </div>
        <div v-show="showDrawer" class="right">
            <n-card title="代码执行细节">
                <n-form ref="moreInfoFormRef" :model="question" size="large">
                    <n-form-item label="完整代码">
                        <n-input
                            v-model:value="question.completeCode"
                            :autosize="{ minRows: 3 }"
                            type="textarea"
                        />
                    </n-form-item>
                    <n-form-item label="执行结果">
                        <n-input v-model:value="question.executionResult" :autosize="{ minRows: 3 }" type="textarea"/>
                    </n-form-item>
                    <n-form-item label="报错信息">
                        <n-input
                            v-model:value="question.errorMessage"
                            type="textarea"
                        />
                    </n-form-item>
                    <n-form-item label="你觉得出错的行">
                        <n-input
                            v-model:value="question.errorRow"
                            type="text"
                        />
                    </n-form-item>
                    <n-form-item label="你觉得出错的列">
                        <n-input
                            v-model:value="question.errorColumn"
                            type="text"
                        />
                    </n-form-item>
                    <n-form-item label="出错代码">
                        <n-input
                            v-model:value="question.errorCode"
                            :autosize="{ minRows: 3 }"
                            type="textarea"
                        />
                    </n-form-item>
                </n-form>
            </n-card>
            <!--<n-card title="一些建议">-->
            <!--    <n-collapse accordion default-expanded-names="1">-->
            <!--        <n-p>-->
            <!--            社区是为了帮助你解决具体的编码、算法或语言问题。<br><br>-->
            <!--            请不要谈论敏感话题。-->
            <!--        </n-p>-->
            <!--        <n-collapse-item name="1" title="总结你的问题">-->
            <!--            <n-ul>-->
            <!--                <n-li>包括关于你的目标细节</n-li>-->
            <!--                <n-li>描述预期和实际结果</n-li>-->
            <!--                <n-li>包括任何错误信息</n-li>-->
            <!--            </n-ul>-->
            <!--        </n-collapse-item>-->
            <!--        <n-collapse-item name="2" title="描述你尝试过什么">-->
            <!--            <n-p>显示你已经尝试过的东西，并告诉我们你发现了什么（在这个网站或其他地方），以及为什么它没有满足你的需求。当你提供研究时，你可以得到更好的答案。</n-p>-->
            <!--        </n-collapse-item>-->
            <!--        <n-collapse-item name="3" title="展示必要的代码">-->
            <!--            <n-p>在适当的时候，分享别人重现你的问题所需的最小代码量(也被称为最小的、可重复的例子)</n-p>-->
            <!--        </n-collapse-item>-->
            <!--    </n-collapse>-->
            <!--</n-card>-->
        </div>
        <!--<n-drawer v-model:show="showDrawer" :width="500">-->
        <!--    <n-drawer-content closable title="代码执行细节">-->
        <!--    </n-drawer-content>-->
        <!--</n-drawer>-->
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { insertQuestion } from '../api/question'
import { NAutoComplete, useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'
import { Plus } from '@vicons/fa'
import { listTags } from '../api/tag'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { fuzzyQuery } from '../utils/mini-lodash'
import { useUserStore } from '../store/user'

window.$message = useMessage()
const message = useMessage()
const userStore = useUserStore()
const formRef = ref(null)
const $router = useRouter()
const question = ref({
    title: '',
    content: '',
    tags: [],
    reward: 0,
    executionResult: '',
    errorMessage: '',
    completeCode: '',
    errorCode: '',
    errorRow: '',
    errorColumn: '',
})
const options = ref([])
const autoCompleteInstRef = ref(null)
const autoCompleteValue = ref('')

watch(autoCompleteInstRef, (value) => {
    if (value) {
        listTags().then(res => {
            options.value = []
            res.data.forEach(tag => {
                options.value.push(tag.name)
            })
        })
        nextTick(() => value.focus())
    }
})

const validateTags = () => {
    let result = [...new Set(question.value.tags)]
    return result.length === question.value.tags.length
}
const validateFirstTag = () => {
    let firstTagName = question.value.tags[0]
    if (firstTagName) {
        const programming_languages = ['C语言', 'C++', 'Java', 'Python', 'JavaScript']
        return programming_languages.includes(firstTagName)
    } else {
        return true
    }

}
const rules = {
    title: {
        required: true,
        message: '请输入标题',
        trigger: 'blur',
    },
    tags: [
        {
            validator: validateTags,
            trigger: 'change',
            message: '标签不能重复！',
        },
        {
            validator: validateFirstTag,
            trigger: 'change',
            message: '第一个标签必须为编程语言！',
        },
    ],
}

const handlePublish = () => {
    formRef.value?.validate(errors => {
        if (!errors) {
            question.value.content = vditor.value.getHTML()
            question.value.completeCode = vditor.value.getValue()
            insertQuestion(question.value).then((res) => {
                    if (res.code === '201') {
                        question.value.content = ''
                        question.value.title = ''
                        question.value.tags = []
                        message.success('发布成功，你获得1积分！')
                        $router.push('/questions')
                    }
                },
            )
        } else {
            message.error('内容校验失败')
        }
    })
}

const vditor = ref(null)
onMounted(() => {
        vditor.value = new Vditor('vditor', {
            after () {
                vditor.value.setValue('', true)
            },
            height: 500,
            width: '100%',
            icon: 'material',
            mode: 'wysiwyg',
            tab: '    ',
            placeholder: '内容描述',
            typewriterMode: true,
            undoDelay: 1500,
            hint: {
                emojiTail: '设置常用表情',
            },
            counter: {
                enable: true,
            },
            preview: {
                hljs: {
                    lineNumber: true,
                    style: 'native',
                },
            },
            toolbar: [
                'emoji', 'headings', 'bold', 'italic',
                'strike', 'link', 'ordered-list', 'check', '|',
                'quote', 'line', 'code', 'inline-code', 'fullscreen',
                'edit-mode', '|', 'undo', 'redo', 'code-theme',
                'content-theme', 'preview', 'help', 'outline',
            ],
        })
    },
)

const isShowTagList = (value) => {
    return !!fuzzyQuery(options.value, value).length
}

const showDrawer = ref(true)
</script>

<style scoped>
.header {
    font-size: 18px;
    margin-bottom: 10px;
}

.flex-container {
    display: flex;
    gap: 1vw;
}

.left {
    width: 70%;
}

.right {
    flex: 1;
}

.editor-container {
    width: 100%;
}
</style>
